package com.example.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.File;

/**
 * @Auther: wangxiaodan
 * @Date:2021/3/26 9:01
 * @Description:
 **/
@Service
public  class SendMailServiceImpl implements SendMailService {
    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String userName;
    /**
     * 发邮件
     * @param msg 消息内容
     * @param target 收件人
     */
    @Override
    public void sendMail(String msg, String target) {
        //创建SimpleMailMessage
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(userName); //发件人
        message.setText(msg); //邮件内容
        message.setSubject("系统验证码");
        message.setTo(target); //收件人
        javaMailSender.send(message);
    }

    /**
     * 邮件内容包含html、附件
     * @param msg
     * @param target
     */
    @Override
    @Async
    public void complexSendMail(String msg, String target) {
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(userName); //发件人
            helper.setTo(target);//收件人
            helper.setSubject("系统通知");
            helper.setText("<h1 style='color:red'>" +msg+"</h1>",true);
            //添加附件
            helper.addAttachment("test.png",
                    new File("C:\\Users\\EDZ\\Desktop\\test.png"));
            helper.addAttachment(MimeUtility.encodeWord("手册.txt","utf-8","B"),
                    new File("C:\\Users\\EDZ\\Desktop\\手册.txt"));
            javaMailSender.send(message);
            System.out.println("=========发送邮件结束=========");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
